package com.lifeng.zk.curator.watch;


import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created by lifeng on 2018/6/15.
 * 监听节点变化
 */
public class NodeChangeListener{
    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        String zkurl = "127.0.0.1:2181";
        //第一种方式 //最后一个参数重试策略
        final CuratorFramework client = CuratorFrameworkFactory.newClient(zkurl, 5000,5000,retryPolicy);
        client.start();
        final NodeCache cache = new NodeCache(client,"/li");
        cache.start();
        //NodeCacheListener 监听当前节点的创建，数据修改
        cache.getListenable().addListener(new NodeCacheListener() {
            public void nodeChanged() throws Exception {
                byte[] res = cache.getCurrentData().getData();
                System.out.println("node data: " + new String(res));
            }
        });

        //监听子节点
        final PathChildrenCache cache1 = new PathChildrenCache(client,"/li",true);
        cache1.start();
        cache1.getListenable().addListener(new PathChildrenCacheListener() {
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                System.out.println("child initdata:"+pathChildrenCacheEvent.getInitialData());
                System.out.println("child data:"+pathChildrenCacheEvent.getData());
                System.out.println("child type:"+pathChildrenCacheEvent.getType());
                switch (pathChildrenCacheEvent.getType()) {
                    case CHILD_ADDED:
                        System.out.println("add:" + pathChildrenCacheEvent.getData());
                        break;
                    case CHILD_UPDATED:
                        System.out.println("update:" + pathChildrenCacheEvent.getData());
                        break;
                    case CHILD_REMOVED:
                        System.out.println("remove:" + pathChildrenCacheEvent.getData());
                        break;
                    default:
                        break;
                }
            }
        });

        Thread.sleep(Integer.MAX_VALUE);
    }
}
